<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert title="添加修改会删除缓存，请谨慎操作" type="warning" show-icon>
      </el-alert>

      <el-row :gutter="20">
        <el-col :span="3">
          <el-button class="goodstypebut" type="primary" @click="addGoodsType"
            >添加商品分类</el-button
          >
        </el-col>

        <el-col :span="3">
          <el-button
            icon="el-icon-delete"
            class="goodstypebut"
            type="danger"
            @click="clearGoodsTypeCache"
            >删除缓存</el-button
          >
        </el-col>
      </el-row>

      <tree-table
        class="treeTable"
        :data="goodsTypeList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        :show-row-hover="false"
        border
      >
        <template slot-scope="scope" slot="priority">
          <el-tag v-if="scope.row.level === 1" size="mini">一级</el-tag>
          <el-tag v-else-if="scope.row.level === 2" type="success" size="mini"
            >二级</el-tag
          >
          <el-tag v-else type="info" size="mini">三级</el-tag>
        </template>

        <template slot-scope="scope" slot="update">
          <el-button
            size="mini"
            icon="el-icon-edit"
            type="primary"
            @click="addGoodsTypePicShow(scope.row.id)"
            >添加轮播图</el-button
          >
          <el-button
            size="mini"
            icon="el-icon-edit"
            type="primary"
            @click="addGoodsWxPicShow(scope.row.id)"
            >添加微信图标</el-button
          >
          <el-button
            size="mini"
            icon="el-icon-edit"
            type="primary"
            @click="updateGoodsTypeShow(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            icon="el-icon-delete"
            type="danger"
            @click="delGoodsTypeById(scope.row.id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryPageInfo.pageNum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="queryPageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加商品分类"
      :visible.sync="addDialogVisible"
      @close="addDialogclose"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="分类名称:" prop="name" label-width="100px">
          <el-input v-model="addForm.name" class="inp"></el-input>
        </el-form-item>

        <el-form-item label="优先级:" prop="priority" label-width="100px">
          <el-input v-model.number="addForm.priority" class="inp"></el-input>
        </el-form-item>

        <el-form-item label="父级分类:" label-width="100px">
          <el-cascader
            change-on-select
            expand-trigger="hover"
            v-model="addCascader"
            :options="parentGoodsTypeList"
            :props="addCascaderProps"
            clearable
            @change="addCascaderHandleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改商品分类"
      :visible.sync="updateDialogVisible"
      @close="updateDialogclose"
      width="50%"
    >
      <el-form
        :model="updateForm"
        :rules="updateFormRules"
        ref="updateFormRef"
        label-width="70px"
      >
        <el-form-item label="分类名称:" prop="name" label-width="100px">
          <el-input v-model="updateForm.name" class="inp"></el-input>
        </el-form-item>

        <el-form-item label="优先级:" prop="priority" label-width="100px">
          <el-input v-model.number="updateForm.priority" class="inp"></el-input>
        </el-form-item>

        <el-form-item label="图片:" label-width="100px">
          <el-upload
            class="avatar-uploader"
            :headers="headObj"
            :action="updateImgUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="this.updateForm.pic"
              :src="this.updateForm.pic"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加轮播图"
      :visible.sync="addPicDialogVisible"
      @close="addPicDialogclose"
      width="50%"
    >
      <!-- <el-form
        :model="addPicForm"
        label-width="70px"
      > -->
      <el-upload
        class="upload-demo"
        :headers="headObj"
        :action="updateImgUrl"
        :on-remove="handleRemove"
        :file-list="fileList"
        :on-success="imgsuccess"
        list-type="picture"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload>

      <!-- </el-form> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPicDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPicDialogSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加微信小图标"
      :visible.sync="addWxPicDialogVisible"
      @close="addWxPicDialogclose"
      width="50%"
    >
      <!-- <el-form
        :model="addPicForm"
        label-width="70px"
      > -->
      <!-- <el-upload
        class="upload-demo"
        :headers="headObj"
        :action="updateImgUrl"
        :on-remove="handleRemove"
        :file-list="fileList"
        :on-success="imgsuccess"
        list-type="picture"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且不超过500kb
        </div>
      </el-upload> -->

      <el-upload
        class="avatar-uploader"
        :headers="headObj"
        :action="updateImgUrl"
        :show-file-list="false"
        :on-success="handleWxPicSuccess"
      >
        <img v-if="wxImageUrl" :src="wxImageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>

      <!-- </el-form> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addWxPicDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addWxPicDialogSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getGoodsTypeData,
  getParentGoodsTypeList,
  addGoodsType,
  getGoodsTypeById,
  updateGoodsType,
  deleteGoodsTypeById,
  clearGoodsTypeCache,
  // uploadTypeImgDel,
  getTypeImgData,
  getWxTypeImgData,
  addPic,
  addWxPic
} from '@/api/goodsType'
export default {
  name: 'GoodsType',
  data () {
    return {
      addWxPicDialogVisible: false,
      updateImgUrl: 'http://192.168.10.1:6002/admin/dictionary/file/UploadImg',
      headObj: {
        AdminAuthorizationToken: this.$store.getters.token
      },
      queryPageInfo: {
        pageNum: 1,
        pageSize: 10
      },
      goodsTypeList: [],
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'name'
        },
        {
          label: '优先级',
          prop: 'priority'
        },
        {
          label: '等级',
          type: 'template',
          template: 'priority'
        },
        {
          label: '等级',
          type: 'template',
          template: 'update'
        }
      ],
      addDialogVisible: false,
      addForm: {
        name: '',
        priority: 0,
        level: 1,
        parentId: 0
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入分类参数', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '长度在 2 到 8 个字符',
            trigger: 'blur'
          }
        ],
        priority: [
          { required: true, message: '请输入优先级', trigger: 'blur' }
        ]
      },
      parentGoodsTypeList: [],
      addCascader: [],
      addCascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      updateDialogVisible: false,
      updateForm: {},
      updateFormRules: {
        name: [
          { required: true, message: '请输入分类参数', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '长度在 2 到 8 个字符',
            trigger: 'blur'
          }
        ],
        priority: [
          { required: true, message: '请输入优先级', trigger: 'blur' }
        ]
      },
      addPicDialogVisible: false,
      // picArr: [],
      fileList: [],
      picListId: '',
      wxImageUrl: '',
      wxTypeId: ''
    }
  },
  methods: {
    addUser () {},
    handleAvatarSuccess (response) {
      this.$message.success('上传成功')
      this.updateForm.pic = response.data
    },
    async getGoodsTypeList () {
      const res = await getGoodsTypeData(this.queryPageInfo)
      // console.log(res)
      this.goodsTypeList = res.data.list
      this.total = res.data.total
    },
    async addGoodsType () {
      this.addDialogVisible = true
      const res = await getParentGoodsTypeList()
      this.parentGoodsTypeList = res.data
    },
    handleSizeChange (pageSize) {
      this.queryPageInfo.pageSize = pageSize
      this.getGoodsTypeList()
    },
    handleCurrentChange (pageNum) {
      this.queryPageInfo.pageNum = pageNum
      this.getGoodsTypeList()
    },
    addDialogclose () {
      this.$refs.addFormRef.resetFields()
      this.addCascader = []
      this.addForm.level = 1
      this.addForm.parentId = 0
    },
    addCascaderHandleChange () {
      if (this.addCascader.length > 0) {
        this.addForm.level = this.addCascader.length + 1
        this.addForm.parentId = this.addCascader[this.addCascader.length - 1]
      } else {
        this.addForm.level = 1
        this.addForm.parentId = 0
      }
    },
    async addDialogSubmit () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return false
        const res = await addGoodsType(this.addForm)
        this.$message.success(res.data)
        this.addDialogVisible = false
        this.getGoodsTypeList()
      })
    },
    async updateGoodsTypeShow (id) {
      this.updateDialogVisible = true
      const res = await getGoodsTypeById(id)
      this.updateForm = res.data
    },
    async updateDialogSubmit () {
      this.$refs.updateFormRef.validate(async (valid) => {
        if (!valid) return false
        const res = await updateGoodsType(this.updateForm)
        this.$message.success(res.data)
        this.getGoodsTypeList()
        this.updateDialogVisible = false
      })
    },
    updateDialogclose () {
      this.$refs.updateFormRef.resetFields()
    },
    async delGoodsTypeById (id) {
      const flag = await this.$confirm(
        '此操作将永久删除该类型, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (flag === 'cancel') {
        this.$message.info('取消删除')
      } else {
        const res = await deleteGoodsTypeById(id)
        this.$message.success(res.data)
        this.getGoodsTypeList()
      }
    },
    async clearGoodsTypeCache () {
      const res = await clearGoodsTypeCache()
      this.$message.success(res.data)
    },
    async addGoodsTypePicShow (id) {
      this.addPicDialogVisible = true
      const res = await getTypeImgData(id)
      this.picListId = id
      if (res.data !== null) {
        this.fileList = res.data
      }
    },
    async addGoodsWxPicShow (id) {
      this.addWxPicDialogVisible = true
      const res = await getWxTypeImgData(id)
      this.wxTypeId = id
      this.wxImageUrl = res.data
    },
    handleWxPicSuccess (res, file) {
      // console.log(res)
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.wxImageUrl = res.data
    },
    async addWxPicDialogSubmit () {
      const obj = {
        typeId: this.wxTypeId,
        imageUrl: this.wxImageUrl
      }
      const res = await addWxPic(obj)
      this.$message.success(res.data)
      this.addWxPicDialogVisible = false
    },
    addWxPicDialogclose () {
      this.wxImageUrl = ''
      this.wxTypeId = ''
      this.addWxPicDialogVisible = false
    },
    addPicDialogclose () {
      this.fileList = []
      this.picListId = ''
      this.addPicDialogVisible = false
    },
    imgsuccess (response) {
      console.log(response)
      const obj = {
        name: '',
        url: response.data
      }
      // this.picArr.push(response)
      this.fileList.push(obj)
    },
    async handleRemove (file) {
      // console.log(file)
      console.log(file)
      // await uploadTypeImgDel(file.response)
      // const index = this.picArr.findIndex((item) => item === file.response)
      // this.addForm.picArr.splice(index, 1)
      const index = this.fileList.findIndex((item) => item.url === file.url)
      console.log(index)
      this.fileList.splice(index, 1)
    },
    async addPicDialogSubmit () {
      const obj = {
        typeId: this.picListId,
        typeList: this.fileList
      }
      const res = await addPic(obj)
      this.$message.success(res.data)
      this.addPicDialogVisible = false
    }
  },
  created () {
    this.getGoodsTypeList()
  }
}
</script>

<style scoped lang="less">
.treeTable {
  margin-top: 15px;
}
// .inp {
//   width: 600px;
// }
.el-cascader {
  width: 600px;
}
.goodstypebut {
  margin-top: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
